
package Vista;

import Modelo.Productos;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class Ventas extends javax.swing.JFrame {
private Controlador.Ventas ventasController;
private DAOMySQL.Productos productosDAO;
private TableRowSorter trsfiltro;

    public Ventas() {
        initComponents();
        setSize(720, 650);
        setResizable(false);
        ventasController = new Controlador.Ventas();
        setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        agregarAlCarro = new javax.swing.JButton();
        completarVenta = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        jLabelTotal = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableCarro = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableBusqueda = new javax.swing.JTable();
        jButtonEliminar = new javax.swing.JButton();
        jTextFieldCantidad = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldBuscar = new javax.swing.JTextField();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Ventas"));

        agregarAlCarro.setText("Agregar al Carrito");
        agregarAlCarro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarAlCarroActionPerformed(evt);
            }
        });

        completarVenta.setText("Completar Venta");
        completarVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                completarVentaActionPerformed(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel12.setText("Total: ");

        jLabelTotal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabelTotal.setText("0");

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Carro de compras"));

        jTableCarro.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nombre", "Plataforma", "Categoria", "Cantidad", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableCarro.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableCarro.getTableHeader().setResizingAllowed(false);
        jTableCarro.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTableCarro);

        jScrollPane3.setBorder(javax.swing.BorderFactory.createTitledBorder("Inventario"));

        jTableBusqueda.setModel(this.getCustomTableModel());
        jTableBusqueda.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableBusqueda.getTableHeader().setResizingAllowed(false);
        jTableBusqueda.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(jTableBusqueda);

        jButtonEliminar.setText("Eliminar del Carrito");
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jTextFieldCantidad.setText("1");
        jTextFieldCantidad.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        jLabel2.setText("Cantidad");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setText("Bienvenidos a GameBae");

        jLabel1.setText("Buscar");

        jTextFieldBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldBuscarKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(completarVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(61, 61, 61)
                                        .addComponent(jLabelTotal)
                                        .addGap(0, 0, Short.MAX_VALUE))))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonEliminar)
                        .addGap(18, 18, 18)
                        .addComponent(agregarAlCarro)
                        .addGap(55, 55, 55)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(agregarAlCarro)
                    .addComponent(jButtonEliminar)
                    .addComponent(jTextFieldCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(completarVenta, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel12)
                        .addComponent(jLabelTotal)))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /**
     * Evento boton "Agregar al Carrito". 
     * Valida cantidad de item a agregar, genera llenado de Jtable compra con los elementos seleccionados
     * junto con calcular el valor a pagar.
     * @param evt 
     */
    private void agregarAlCarroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarAlCarroActionPerformed
        if(this.jTextFieldCantidad.getText().equals("0")){
            JOptionPane.showMessageDialog(null, "Cantidad no puede ser 0", "ERROR", JOptionPane.ERROR_MESSAGE);
            this.jTextFieldCantidad.setText("1");
        }else if(this.jTextFieldCantidad.getText().isEmpty()){
            JOptionPane.showMessageDialog(null, "Favor ingrese una cantidad", "ERROR", JOptionPane.ERROR_MESSAGE);
            this.jTextFieldCantidad.setText("1");
        }else{ 
            try{
                DefaultTableModel modelo = (DefaultTableModel) jTableCarro.getModel();
                // Setea valores seleccionados en carro compra
                Object[] fila = new Object[6];
                fila[0] = jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),0).toString();
                fila[1] = jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),1).toString();
                fila[2] = jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),2).toString();
                fila[3] = jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),3).toString();
                fila[4] = jTextFieldCantidad.getText();
                fila[5] = jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),5).toString();
                modelo.addRow(fila);
                this.jTableCarro.setModel(modelo);
                // Calcula valor venta
                int Total = Integer.parseInt(this.jLabelTotal.getText()) + Integer.parseInt(jTableBusqueda.getValueAt(this.jTableBusqueda.getSelectedRow(),5).toString())*Integer.parseInt(this.jTextFieldCantidad.getText());
                this.jLabelTotal.setText(String.valueOf(Total));
                this.jTextFieldCantidad.setText("1");     
                }
            catch (ArrayIndexOutOfBoundsException e){
                System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
                JOptionPane.showMessageDialog(null, "Seleccione un item del Inventario", "ERROR", JOptionPane.ERROR_MESSAGE);
            } 
        }
        // Limpia valores de busqueda
        this.jTextFieldBuscar.setText("");
        jTextFieldBuscarKeyReleased(null);
    }//GEN-LAST:event_agregarAlCarroActionPerformed
    /**
     * Evento boton "Eliminar del Carrito"
     * Realiza eliminacion de row seleccionado en jtable carro descontando su valor al Total
     * @param evt 
     */
    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) jTableCarro.getModel();
        try{
            int Total = Integer.parseInt(this.jLabelTotal.getText()) - 
                    Integer.parseInt(jTableCarro.getValueAt(this.jTableCarro.getSelectedRow(),5).toString())
                    *Integer.parseInt(jTableCarro.getValueAt(this.jTableCarro.getSelectedRow(),4).toString());
            this.jLabelTotal.setText(String.valueOf(Total));
            modelo.removeRow(jTableCarro.getSelectedRow());
            }
         catch (ArrayIndexOutOfBoundsException e){
             System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
             JOptionPane.showMessageDialog(null, "Seleccione un item del carro de compras", "ERROR", JOptionPane.ERROR_MESSAGE);
         }    
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    /**
     * Evento boton "Completar Venta"
     * Genera update a la DB para cada producto en el jtable carro descontando la cantidad vendida
     * Finaliza la venta limpiando campos y recargando la tabla inventario
     * @param evt 
     */
    private void completarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_completarVentaActionPerformed
        if (this.jTableCarro.getRowCount() < 1) {
            JOptionPane.showMessageDialog(null, "Debe agregar al menos un pruducto al carro","ERROR", JOptionPane.ERROR_MESSAGE);
        }else{
            this.productosDAO = new DAOMySQL.Productos();
            DefaultTableModel modelo = (DefaultTableModel) jTableCarro.getModel();
            this.jTableCarro.setModel(modelo);
            // Actualiza stock x c/u de los item vendidos
            for (int i = 0; i < this.jTableCarro.getRowCount() ; i++) {
                productosDAO.actualizaStock(this.jTableCarro.getValueAt(i,0).toString(),this.jTableCarro.getValueAt(i,4).toString());          
            }
            // Limpia carro 
            try{
                while(modelo.getRowCount()>0){
                modelo.removeRow(0);}
            }
            catch(Exception e){
                System.out.println("Error al limpiar carrito");
            }
        JOptionPane.showMessageDialog(null, "Venta realizada: $"+jLabelTotal.getText(),"OK", JOptionPane.INFORMATION_MESSAGE);
        // Limpia formulario.
        this.jLabelTotal.setText("0");
        this.jTextFieldBuscar.setText("");
        jTableBusqueda.setModel(this.getCustomTableModel());
        }
    }//GEN-LAST:event_completarVentaActionPerformed
    
    /**
     * Evento de campo busqueda.
     * Filtra contenido de inventario por no,bre de juego, mostrando solo el match entre lo escrito
     * y lo encontrado.
     * @param evt 
     */
    private void jTextFieldBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldBuscarKeyReleased
        DefaultTableModel modeloStock = (DefaultTableModel) jTableBusqueda.getModel();
        trsfiltro = new TableRowSorter(modeloStock);
        jTableBusqueda.setRowSorter(trsfiltro);
        // (?!) case insensitive al campo buscar
        trsfiltro.setRowFilter(RowFilter.regexFilter("(?i)"+jTextFieldBuscar.getText(), 1));
    }//GEN-LAST:event_jTextFieldBuscarKeyReleased
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Ventas().setVisible(true);
            }
        });
    }
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarAlCarro;
    private javax.swing.JButton completarVenta;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelTotal;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableBusqueda;
    private javax.swing.JTable jTableCarro;
    private javax.swing.JTextField jTextFieldBuscar;
    private javax.swing.JTextField jTextFieldCantidad;
    // End of variables declaration//GEN-END:variables

    /** 
     * Metodo para llenado de jtable inventario
     * @return 
     */
    private TableModel getCustomTableModel(){
        this.ventasController = new Controlador.Ventas();
        return new javax.swing.table.DefaultTableModel(
                this.ventasController.getContenidoJTable(),
                this.ventasController.getCabeceraJTable()
            ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,java.lang.String.class,java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
    }
}
// END